package com.yl.chainStore.services.impl.warehouse

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
import com.yl.chainStore.common.LockObjects
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.warehouse.WarehouseInOrder
import com.yl.chainStore.entity.warehouse.WarehouseInOrderDetail
import com.yl.chainStore.mapper.warehouse.WarehouseInOrderDetailMapper
import com.yl.chainStore.mapper.warehouse.WarehouseInOrderMapper
import com.yl.chainStore.pojo.vo.warehouse.UpdateWarehouseGoodVo
import com.yl.chainStore.services.warehouse.IWarehouseInOrderService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class WarehouseInOrderServiceImpl(
	private val warehouseInOrderMapper: WarehouseInOrderMapper,
	private val warehouseInOrderDetailMapper: WarehouseInOrderDetailMapper,
) : IWarehouseInOrderService {

	companion object {
		private val log = LoggerFactory.getLogger(IWarehouseInOrderService::class.java)
	}

	@Autowired
	lateinit var iWarehouseService: IWarehouseService

	override fun addDetail(detail: WarehouseInOrderDetail): ResponseBody {
		log.info("入库单 =>入库单添加明细：detail{}", detail)
		warehouseInOrderDetailMapper.insert(detail)
		return returnSuccess()
	}

	override fun getInOrder(id: Long): WarehouseInOrder? {
		log.info("入库单：入库单基础信息查询：id{}", id)
		return warehouseInOrderMapper.getInOrderDetail(id)
	}

	override fun inOrderDetails(orderId: Long): List<WarehouseInOrderDetail> {
		log.info("入库单：入库单明细查询：orderId{}", orderId)
		return warehouseInOrderDetailMapper.getListByInOrderId(orderId)
	}

	override fun updateInOrder(inOrder: WarehouseInOrder): ResponseBody {
		log.info("入库单管理：修改入库信息：inOrder{}", inOrder)
		if (inOrder.id == -1L) {
			return returnError(ErrorCode.PARAM_EMPTY, "未找到修改对象")
		}
		val selectById =
			warehouseInOrderMapper.selectById(inOrder.id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到修改对象")
		if (selectById.status.code > Status.WAIT_AUDIT.code) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "不能修改此订单")
		}
		warehouseInOrderMapper.updateById(inOrder)
		return returnSuccess()
	}

	override fun updateInOrderDetail(detail: WarehouseInOrderDetail): ResponseBody {
		log.info("入库单管理：修改入库明细：detail{}", detail)
		val warehouseInOrderDetail =
			warehouseInOrderDetailMapper.selectById(detail.id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if(warehouseInOrderDetail.status.code > Status.WAIT_AUDIT.code){
			return returnError(ErrorCode.DATA_SAVE_FAILED,"物品已被处理，不可修改")
		}
		if (detail.itemId == -1L) {
			return returnError(ErrorCode.PARAM_EMPTY, "请选择物品")
		}
		if(detail.goodCount <= 0){
			return returnError(ErrorCode.PARAM_EMPTY, "请填写入库数量")
		}
		warehouseInOrderDetailMapper.updateById(detail)
		return returnSuccess()
	}

	override fun delInOrderDetail(detailId: Long): ResponseBody {
		log.info("仓库订单管理：删除明细：detailId{}", detailId)
		val warehouseInOrderDetail =
			warehouseInOrderDetailMapper.selectById(detailId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if(warehouseInOrderDetail.status.code > Status.WAIT_AUDIT.code){
			return returnError(ErrorCode.DATA_SAVE_FAILED,"物品已被处理，不可修改")
		}
		warehouseInOrderDetailMapper.deleteById(detailId)
		return returnSuccess()
	}

	override fun completeInOrder(orderId: Long): ResponseBody {
		log.info("仓库订单管理：订单审核通过：orderId：{}", orderId)
		val order =
			warehouseInOrderMapper.selectById(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到入库单")
		val list = warehouseInOrderDetailMapper.getListByInOrderId(orderId)
		order.details = list
		return completeInOrder(order)
	}

	override fun completeInOrder(inOrder: WarehouseInOrder): ResponseBody {
		//目前需要完整数据
		log.info("仓库订单管理：入库确认：inOrder{}", inOrder)
		if (inOrder.details.isNullOrEmpty()) {
			return returnError(ErrorCode.PARAM_EMPTY, "没有物品")
		}
		if (inOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		inOrder.status = Status.COMPLETE
		inOrder.dealUserId = getContext().userId
		inOrder.dealTime = Date()
		warehouseInOrderMapper.updateById(inOrder)
		val str :String = inOrder.companyId.toString() + "_"+inOrder.deptId.toString()
		synchronized(LockObjects.getWarehouseLock(str)){
			for (detail in inOrder.details!!) {
				log.info("仓库订单管理：入库确认：明细确认（入库）：detail{}", detail)
				detail.status = Status.COMPLETE

				//组装入库记录 然后入库
				val log = UpdateWarehouseGoodVo(
					associatedType = TypeEnum.WAREHOUSE_LOG_TYPE_IN_ORDER,
					associatedId = inOrder.id,
					remark = detail.remark,
					deptId = inOrder.deptId,
					companyId = inOrder.companyId,
					itemId = detail.itemId,
					goodCount = detail.goodCount,
					unitPrice = detail.goodPrice,
					detailId = detail.id
				)

				val inWarehouse = iWarehouseService.inWarehouse(null,log)
				if (inWarehouse.code != ErrorCode.SUCCESS.code) {
					return inWarehouse
				}
				warehouseInOrderDetailMapper.updateById(detail)
			}

		}

		return returnSuccess()
	}

	override fun noPassInOrder(id: Long):ResponseBody{
		log.info("入库单管理：审核不通过：id{}", id)
		val inOrder = warehouseInOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if (inOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		inOrder.dealUserId = getContext().userId
		inOrder.status = Status.NO_PASS
		warehouseInOrderMapper.updateById(inOrder)
		warehouseInOrderDetailMapper.update(
			null,
			UpdateWrapper<WarehouseInOrderDetail?>().set("status", Status.NO_PASS).eq("in_order_id", id)
		)

		return returnSuccess()
	}

	override fun cancelInOrder(id: Long): ResponseBody {
		log.info("入库单管理：取消入库：id{}", id)
		val inOrder = warehouseInOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if (inOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		inOrder.dealUserId = getContext().userId
		inOrder.status = Status.SCRAP
		warehouseInOrderMapper.updateById(inOrder)
		warehouseInOrderDetailMapper.update(
			null,
			UpdateWrapper<WarehouseInOrderDetail?>().set("status", Status.SCRAP).eq("in_order_id", id)
		)

		return returnSuccess()
	}

	override fun deleteInOrder(id: Long): ResponseBody {
		log.info("入库单 ==>入库单删除：id{}", id)
		val inOrder = warehouseInOrderMapper.selectById(id)?: return returnSuccess()
		if(inOrder.status.code > Status.WAIT_AUDIT.code){
			return returnError(ErrorCode.DATA_DELETE_FAILED,"订单已被处理")
		}
		warehouseInOrderMapper.deleteById(id)
		return returnSuccess()
	}

}
